<template>
	<div class="mod-transport">
		<avue-crud ref="crud" :page="page" :data="dataList" :option="tableOption" :span-method="spanMethod"
			@search-change="searchChange" @selection-change="selectionChange" @on-load="getDataList">
			<template slot-scope="scope" slot="prodPropValues">
				<el-tag v-for="item in scope.row.prodPropValues" :key="item.valueId">{{ item.propValue }}
				</el-tag>
			</template>
		</avue-crud>
	</div>
</template>

<script>
import { tableOption } from '@/crud/shop/okr'
export default {
	data() {
		return {
			dataForm: {
				transName: ''
			},
			dataList: [],
			dataListLoading: false,
			dataListSelections: [],
			addOrUpdateVisible: false,
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10 // 每页显示多少条
			},
			tableOption: tableOption,
			spanArr: [
				{ prop: 'okr', span: [] },
				{ prop: 'plan', span: [] },
				{ prop: 'bgplan', span: [] },
				{ prop: 'solveplan', span: [] },
				{ prop: 'source', span: [] },
				{ prop: 'grade', span: [] }
			]
		}
	},
	components: {

	},
	mounted() {
		this.rowSort();
		this.rowCalc();
	},
	methods: {
		transformData(apiData) {
			const records = apiData || [];
			let globalIndex = 1; // 全局序号计数器

			return records.flatMap(record => {
				// 提取所有子列表
				const krList = record.crmOkrKrList || [];
				const resList = record.crmOkrResmeasureList || [];
				const solutionList = record.crmOkrSolutionList || [];
				const pessimismList = record.crmOkrPessimismList || [];

				// 计算各列最大行数（独立计算）
				const mergeConfig = {
					okr: 1,                 // OKR始终合并
					measure: resList.length || 1,
					solution: solutionList.length || 1,
					pessimism: pessimismList.length || 1,
					kr: krList.length || 1
				};

				// 生成行列映射表
				const matrix = [];
				const maxRows = Math.max(...Object.values(mergeConfig));

				for (let i = 0; i < maxRows; i++) {
					matrix.push({
						// 合并控制字段
						_merge: {
							okr: i === 0 ? maxRows : 0,   // OKR合并所有行
							measure: i < mergeConfig.measure ? 1 : 0,
							solution: i < mergeConfig.solution ? 1 : 0,
							pessimism: i < mergeConfig.pessimism ? 1 : 0,
							kr: i < mergeConfig.kr ? 1 : 0
						},

						// 数据字段
						seq: globalIndex++,
						krResult: i === 0 ? record.krResult : '', // 仅第一行显示OKR
						krDesc: krList[i]?.krDesc || '—',
						resmesureDesc: resList[i]?.resmesureDesc || '—',
						solutionDesc: solutionList[i]?.solutionDesc || '—',
						pessimismDesc: pessimismList[i]?.pessimismDesc || '—'
					});
				}

				return matrix;
			});
		},
		// 获取数据列表
		getDataList(page, params, done) {
			this.dataListLoading = true
			this.$http({
				url: this.$http.adornUrl('/crm/okr/pageOkrMainAll'),
				method: 'get',
				params: this.$http.adornParams(
					Object.assign(
						{
							current: page == null ? this.page.currentPage : page.currentPage,
							size: page == null ? this.page.pageSize : page.pageSize
						},
						params
					)
				)
			}).then(({ data }) => {

				this.dataList = this.transformData(data.obj.records)
				this.page.total = data.obj.total;
				console.log('this.dataList:', this.dataList);
				this.dataListLoading = false
				if (done) {
					done()
				}
			})
		},
		// 删除
		deleteHandle(id) {
			var ids = id ? [id] : this.dataListSelections.map(item => { return item.transportId })
			this.$confirm(
				`确定进行[${id ? '删除' : '批量删除'}]操作?`,
				'友情提醒',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			).then(() => {
				this.$http({
					url: this.$http.adornUrl('/shop/transport'),
					method: 'delete',
					data: this.$http.adornData(ids, false)
				}).then(({ data }) => {
					this.$message({
						message: '操作成功',
						type: 'success',
						duration: 1500,
						onClose: () => {
							// this.getDataList(this.page)
							this.refreshChange()
						}
					})
				})
			}).catch((e) => {
				console.log('e: ', e)
			})
		},
		rowCalc() {
			this.spanArr.forEach((ele, index) => {
				let parent;
				if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span;
				ele.span = this.rowSpan(ele.prop, parent);
			});
		},
		rowSort() {
			let propList = this.spanArr.map(ele => ele.prop);
			this.spanArr.forEach((ele, index) => {
				let key = ele.prop;
				this.dataList = this.dataList.sort((a, b) => {
					let flag = true;
					for (let i = 0; i < index; i++) {
						let prop = this.spanArr[i].prop;
						flag = flag && a[prop] == b[prop];
					}
					if (flag) {
						if (a[key] < b[key]) { return 1; }
						else if (a[key] > b[key]) { return -1; }
						return 0;
					}
					return 0;
				});
			});
		},
		rowSpan(key, parent) {
			let list = [];
			let position = 0;
			this.dataList.forEach((item, index) => {
				if (index === 0) {
					list.push(1);
					position = 0;
				} else {
					if (this.dataList[index][key] === this.dataList[index - 1][key]) {
						if (parent && parent[index] !== 0) {
							list.push(1);
							position = index;
						} else {
							list[position] += 1;
							list.push(0);
						}
					} else {
						list.push(1);
						position = index;
					}
				}
			});
			return list;
		},
		spanMethod({ row, column, rowIndex, columnIndex }) {
			// const property = column.property;
			// const mergeInfo = row._merge[property];

			// // 需要合并的列
			// if (mergeInfo !== undefined) {
			// 	return {
			// 		rowspan: mergeInfo,
			// 		colspan: mergeInfo > 0 ? 1 : 0
			// 	};
			// }

			// // 普通列不合并
			// return { rowspan: 1, colspan: 1 };


		},
		// 条件查询
		searchChange(params, done) {
			this.getDataList(this.page, params, done)
		},
		// 刷新回调用
		refreshChange() {
			this.page = this.$refs.crud.$refs.tablePage.defaultPage
			this.getDataList(this.page)
			this.dataListSelections = []
			this.$refs.crud.selectClear()
		},
		// 多选变化
		selectionChange(val) {
			console.log('val: ', val)
			this.dataListSelections = val
		}
	}
}
</script>
